/*
 * StartupFrame.java
 *
 * Created on 2007/2/3 12:45
 */
package org.sais.eswn.ui;

import org.sais.eswn.core.GameCore;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
import org.sais.eswn.deck.DeckEditorWindow;
import org.sais.eswn.net.ClientSock;
import org.sais.eswn.net.HostSock;
import org.sais.eswn.net.ISockCallback;
import org.sais.eswn.tool.Tools;

/**
 *
 * @author  Romulus
 */
public class StartupFrame extends javax.swing.JFrame implements ISockCallback {

    boolean noupdate = false;
    HostSock mHostSock;

    public StartupFrame() throws Exception {
        // this.setIconImage(new ImageIcon(new ReadInnerFile("mainicongray.jpg").u).getImage());
        if (!new File("nodebug").exists()) {  //Debug Mode, to disable log put a nodebug at excuteroot
            System.setOut(new PrintStream(new FileOutputStream("message_play.log")));
            System.setErr(new PrintStream(new FileOutputStream("message_error.log")));
        }
        initComponents();

        this.setLocation(200, 140);
        this.setVisible(true);
        _versionlabel.setText(GameCore.sVersion);
        this.setTitle(GameCore.sDisplayTitle);
        readconfig();
        if (!new File("nodebug").exists()) {  //Debug Mode, to disable log put a nodebug at excuteroot
      /*if (version.contains("p")) {
            noupdate = true;
            }
            if (version.contains("k")) {
            noupdate = true;
            }*/
        }

        if (Tools.readConfig("originalcard").toLowerCase().equals("true")) {
            this.setTitle("Easten Silver Wing's Note " + GameCore.sVersion);
        }

        Tools.readCardBase();

    }

    //Functions
    /**
     * For class loaders.
     * @return The program's version.
     */
    public static String getVersion() {
        return GameCore.sVersion;
    }

    private void host() {
        try {
            if (mHostSock == null) {
                mHostSock = new HostSock(this, Tools.safeParseInt(_port.getText()), _hn.getText());
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Host() in Startup", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }

    }

    private void HostDisconnect() {
        if (mHostSock != null) {
            mHostSock.closeSocket();
        }
    }

    private void client() {
        try {
            _networkclient.setEnabled(false);
            ClientSock check = new ClientSock(this, _ip.getText(), Tools.safeParseInt(_port.getText()), _hn.getText(), false);
        } catch (ConnectException ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Client() in Startup", JOptionPane.ERROR_MESSAGE);
            _messagebar.setText("Failed to connect to host.");
        } catch (SocketTimeoutException ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Client() in Startup", JOptionPane.ERROR_MESSAGE);
            _messagebar.setText("Failed to connect to host.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Client() in Startup", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }

        _networkclient.setEnabled(true);
    }

    private void watch() {
        try {
            _networkwatch.setEnabled(false);
            ClientSock check = new ClientSock(this, _ip.getText(), Tools.safeParseInt(_port.getText()), _hn.getText(), true);
        } catch (ConnectException ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Client() in Startup", JOptionPane.ERROR_MESSAGE);
            _messagebar.setText("Failed to connect to host.");
        } catch (SocketTimeoutException ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Client() in Startup", JOptionPane.ERROR_MESSAGE);
            _messagebar.setText("Failed to connect to host.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "Client() in Startup", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }

        _networkwatch.setEnabled(true);
    }

    public void setMessage(String message) {
        _messagebar.setText(message);
    }

    void readconfig() {
        if (!Tools.readConfig("name").equals("")) {
            _hn.setText(Tools.readConfig("name"));
        }

        if (Tools.readConfig("semiautoupdate").toLowerCase().equals("off")) {
            noupdate = true;
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        _title = new javax.swing.JLabel();
        _versionlabel = new javax.swing.JLabel();
        _networkhost = new javax.swing.JButton();
        _deckeditor = new javax.swing.JButton();
        _exit = new javax.swing.JButton();
        _hn = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        _ip = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        _port = new javax.swing.JTextField();
        _networkclient = new javax.swing.JButton();
        _messagebar = new javax.swing.JTextField();
        _networkwatch = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(498, 390));

        _title.setFont(new java.awt.Font("ＤＦＰ魏碑体W7", 0, 48));
        _title.setForeground(new java.awt.Color(153, 153, 153));
        _title.setText("東方銀翼札");

        _versionlabel.setFont(new java.awt.Font("Times New Roman", 0, 24));
        _versionlabel.setText("Ver ");

        _networkhost.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        _networkhost.setText("NETWORK MODE - HOST");
        _networkhost.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _networkhostActionPerformed(evt);
            }
        });

        _deckeditor.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        _deckeditor.setText("DECK EDITOR");
        _deckeditor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _deckeditorActionPerformed(evt);
            }
        });

        _exit.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        _exit.setText("EXIT");
        _exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _exitActionPerformed(evt);
            }
        });

        _hn.setBackground(new java.awt.Color(238, 255, 255));
        _hn.setFont(new java.awt.Font("MS PGothic", 0, 18)); // NOI18N
        _hn.setText("名前がない程度の能力");
        _hn.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                _hnFocusLost(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        jLabel3.setText("HN");

        jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        jLabel5.setText("CONNECT TO");

        _ip.setBackground(new java.awt.Color(238, 255, 255));
        _ip.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N

        jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        jLabel6.setText("PORT");

        _port.setBackground(new java.awt.Color(238, 255, 255));
        _port.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
        _port.setText("12700");

        _networkclient.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        _networkclient.setText("NETWORK MODE - CLIENT");
        _networkclient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _networkclientActionPerformed(evt);
            }
        });

        _messagebar.setBackground(new java.awt.Color(255, 244, 246));
        _messagebar.setEditable(false);
        _messagebar.setFont(new java.awt.Font("MS PGothic", 0, 14)); // NOI18N
        _messagebar.setText("Stand by ready.");

        _networkwatch.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        _networkwatch.setText("NETWORK MODE - WATCH");
        _networkwatch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _networkwatchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(_networkhost))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(_networkclient))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(_networkwatch))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(_deckeditor)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(_hn, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(_port, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(_ip, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
            .addGroup(layout.createSequentialGroup()
                .addGap(110, 110, 110)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(_title, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(230, 230, 230)
                        .addComponent(_versionlabel, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(_exit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(_messagebar, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(_title, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addComponent(_versionlabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(_networkhost)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(_hn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(_networkclient)
                        .addGap(3, 3, 3)
                        .addComponent(_networkwatch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(_deckeditor))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(_port, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(_ip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(63, 63, 63)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(_exit)
                    .addComponent(_messagebar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

  private void _deckeditorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__deckeditorActionPerformed
      try {
          DeckEditorWindow dew;
          dew =
                  new DeckEditorWindow(GameCore.sVersion);
          dew.setVisible(true);
      } catch (Exception ex) {
          ex.printStackTrace();
      }
}//GEN-LAST:event__deckeditorActionPerformed

   private void _hnFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event__hnFocusLost
       try {
           Tools.updateConfig("name", _hn.getText());
       } catch (Exception ex) {
           ex.printStackTrace();
       }
}//GEN-LAST:event__hnFocusLost

   private void _networkclientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__networkclientActionPerformed
       _messagebar.setText("Connecting...");
       HostDisconnect();

       client();
}//GEN-LAST:event__networkclientActionPerformed

   private void _networkhostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__networkhostActionPerformed
       _messagebar.setText("Waiting for Connection...");
       host();
   }//GEN-LAST:event__networkhostActionPerformed

   private void _exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__exitActionPerformed
       System.exit(0);
}//GEN-LAST:event__exitActionPerformed

   private void _networkwatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__networkwatchActionPerformed
       watch();
}//GEN-LAST:event__networkwatchActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        Tools.setLocale();
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new StartupFrame();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton _deckeditor;
    private javax.swing.JButton _exit;
    private javax.swing.JTextField _hn;
    private javax.swing.JTextField _ip;
    private javax.swing.JTextField _messagebar;
    private javax.swing.JButton _networkclient;
    private javax.swing.JButton _networkhost;
    private javax.swing.JButton _networkwatch;
    private javax.swing.JTextField _port;
    private javax.swing.JLabel _title;
    private javax.swing.JLabel _versionlabel;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    // End of variables declaration//GEN-END:variables
}
